<template>
  <z-modal
    centered
    :title="name + '选择'"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    @cancel="close"
    cancelText="关闭"
  >
    <a-row :gutter="18">
      <a-col :span="16">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" class="table-page-search-form">
            <a-row :gutter="24">
              <a-col :span="14">
                <a-form-item :label="(queryParamText||name)">
                  <a-input v-model="queryParam[queryParamCode||valueKey]" :placeholder="'请输入' + (queryParamText||name)" @pressEnter="searchQuery"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item>
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <vxe-grid
          border
          ref="vxeTable"
          :rowId="rowKey"
          :height="null"
          :loading="loading"
          :columns="columns || []"
          :data="dataSource || []"
          :checkbox-config="{trigger:'row'}"
          :pagerConfig="{
            pageSize: 10,
            currentPage:ipagination.currentPage,
            total:ipagination.total,
            layouts:layouts
          }"
          @checkbox-change="onSelectChange"
          @checkbox-all="onSelectChange"
        >
        </vxe-grid>
      </a-col>
      <a-col :span="8">
        <!-- <a-card :title="'已选' + name" :bordered="false" :head-style="{padding:0}" :body-style="{padding:0}"> -->
          <div>
            <span style="display: inline-block;height: 40px;line-height: 40px;font-size: 16px;font-weight: 600;">{{'已选' + name}}</span>
            <vxe-grid
              border
              :rowId="rowKey"
              :height="null"
              :columns="selectedTable.columns || []"
              :data="selectedTable.dataSource || []"
            >
              <template #action="{ row,rowIndex }">
                <a @click="handleDeleteSelected(row, rowIndex)">删除</a>
              </template>
            </vxe-grid>
          </div>
      </a-col>
    </a-row>
  </z-modal>
</template>

<script>
import { getAction } from '@/services/manage'
import { VxeTableMixin } from '@/mixins/VxeTableMixin'

export default {
  name: 'JSelectBizComponentModal',
  mixins: [VxeTableMixin],
  props: {
    value: {
      type: Array,
      default: () => []
    },
    visible: {
      type: Boolean,
      default: false
    },
    valueKey: {
      type: String,
      required: true
    },
    multiple: {
      type: Boolean,
      default: true
    },
    width: {
      type: Number,
      default: 900
    },

    name: {
      type: String,
      default: ''
    },
    listUrl: {
      type: String,
      required: true,
      default: ''
    },
    // 根据 value 获取显示文本的地址，例如存的是 username，可以通过该地址获取到 realname
    valueUrl: {
      type: String,
      default: ''
    },
    displayKey: {
      type: String,
      default: null
    },
    columns: {
      type: Array,
      required: true,
      default: () => []
    },
    // 查询条件Code
    queryParamCode: {
      type: String,
      default: null
    },
    // 查询条件文字
    queryParamText: {
      type: String,
      default: null
    },
    rowKey: {
      type: String,
      default: 'id'
    },
    // 过长裁剪长度，设置为 -1 代表不裁剪
    ellipsisLength: {
      type: Number,
      default: 12
    }
  },
  data() {
    return {
      innerValue: [],
      // 已选择列表
      selectedTable: {
        pagination: false,
        scroll: { y: 240 },
        columns: [
          {
            ...this.columns[1]
          },
          {
            title: '操作',
            field: 'action',
            slots: { default: 'action' },
            align: 'center',
            width: 60
          }
        ],
        dataSource: []
      },
      url: { list: this.listUrl },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      options_: [],
      dataSourceMap: {}
    }
  },
  computed: {
    // 表头
    innerColumns() {
      const columns = JSON.parse(JSON.stringify(this.columns))
      columns.forEach(column => {
        // 给所有的列加上过长裁剪
        if (this.ellipsisLength !== -1) {
          column.ellipsis = true
        }
      })
      return columns
    }
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        this.innerValue = JSON.parse(JSON.stringify(val))
        this.selectedRowKeys = []
        this.valueWatchHandler(val)
        this.queryOptionsByValue(val)
      }
    },
    dataSource: {
      deep: true,
      handler(val) {
        console.log(val)
        this.emitOptions(val)
        this.valueWatchHandler(this.innerValue)
      }
    },
    selectedRowKeys: {
      immediate: true,
      deep: true,
      handler(val) {
        this.selectedTable.dataSource = val.map(key => {
          for (const data of this.dataSource) {
            if (data[this.rowKey] === key) {
              this.pushIfNotExist(this.innerValue, data[this.valueKey])
              return data
            }
          }
          for (const data of this.selectedTable.dataSource) {
            if (data[this.rowKey] === key) {
              this.pushIfNotExist(this.innerValue, data[this.valueKey])
              return data
            }
          }
          console.warn('未找到选择的行信息，key：' + key)
          return {}
        })
      }
    }
  },
  methods: {

    /** 关闭弹窗 */
    close() {
      this.$emit('update:visible', false)
    },

    valueWatchHandler(val) {
      val.forEach(item => {
        this.dataSource.concat(this.selectedTable.dataSource).forEach(data => {
          if (data[this.valueKey] === item) {
            this.pushIfNotExist(this.selectedRowKeys, data[this.rowKey])
          }
        })
      })
    },
    pushIfNotExist(array, value, key) {
      for (const item of array) {
        if (key && (item[key] === value[key])) {
          return false
        } else if (item === value) {
          return false
        }
      }
      array.push(value)
      return true
    },
    queryOptionsByValue(value) {
      if (!value || value.length === 0) {
        return
      }
      // 判断options是否存在value，如果已存在数据就不再请求后台了
      let notExist = false
      for (const val of value) {
        let find = false
        for (const option of this.options_) {
          if (val === option.value) {
            find = true
            break
          }
        }
        if (!find) {
          notExist = true
          break
        }
      }
      if (!notExist) return
      getAction(this.valueUrl || this.listUrl, {
        // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
        [this.valueKey]: value.join(',') + ',',
        pageNo: 1,
        pageSize: value.length
      }).then((res) => {
        if (res.success) {
          let dataSource = res.result
          if (!(dataSource instanceof Array)) {
            dataSource = res.result.records
          }
          this.emitOptions(dataSource, (data) => {
            this.pushIfNotExist(this.innerValue, data[this.valueKey])
            this.pushIfNotExist(this.selectedRowKeys, data[this.rowKey])
            this.pushIfNotExist(this.selectedTable.dataSource, data, this.rowKey)
          })
        }
      })
    },

    emitOptions(dataSource, callback) {
      dataSource.forEach(data => {
        const key = data[this.valueKey]
        this.dataSourceMap[key] = JSON.parse(JSON.stringify(data))
        this.pushIfNotExist(this.options_, { label: data[this.displayKey || this.valueKey], value: key }, 'value')
        typeof callback === 'function' ? callback(data) : ''
      })
      this.$emit('options', this.options_, this.dataSourceMap)
    },

    /** 完成选择 */
    handleOk() {
      const value = this.selectedTable.dataSource.map(data => data[this.valueKey])
      this.$emit('input', value)
      this.$emit('ok', value)
      this.close()
    },

    /** 删除已选择的 */
    handleDeleteSelected(record, index) {
      this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]), 1)
      this.selectedTable.dataSource.splice(index, 1)
      this.selectionRows.forEach(item => {
        if (item[this.rowKey] === record[this.rowKey]) {
          this.$refs.vxeTable.setCheckboxRow(item, false)
        }
      })
    },

    customRowFn(record) {
      return {
        on: {
          click: () => {
            const key = record[this.rowKey]
            if (!this.multiple) {
              this.selectedRowKeys = [key]
              this.selectedTable.dataSource = [record]
            } else {
              const index = this.selectedRowKeys.indexOf(key)
              if (index === -1) {
                this.selectedRowKeys.push(key)
                this.selectedTable.dataSource.push(record)
              } else {
                this.handleDeleteSelected(record, index)
              }
            }
          }
        }
      }
    }

  }
}
</script>
<style>
.table-page-search-form .ant-form-item {
  display: flex;
}

.table-page-search-form .ant-form-item-control-wrapper {
  flex: 1;
}
</style>
